package com.app.piemoment;

import static android.view.ViewGroup.LayoutParams.FILL_PARENT;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.app.piemoment.config.Config;
import com.app.piemoment.entity.LoginInfo;
import com.app.piemoment.net.NetService;

public class ComplateUserInfo5Activity extends Activity {
	protected static final int SELECT_PHOTO_REQUEST_CODE = 2015;

	private static final int GET_IMAGE = 2016;

	LinearLayout pic1, pic2;
	SharedPreferences userInfo;
	public ImageView pic_image1, pic_image2;
	public LinearLayout pic1_layout, pic2_layout;

	Button ok_Button;
	private String[] picSelect = new String[] { "拍照", "图库" };
	private static String uploadUrlString = "/api/rest/users/"
			+ LoginInfo.getInstance().getPuid() + "/photos.json";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regedit_info_step5);
		userInfo = getSharedPreferences(BaseActivity.PREF_NAME,
				MODE_WORLD_READABLE);

		pic1 = (LinearLayout) findViewById(R.id.pic1);
		pic_image1 = (ImageView) findViewById(R.id.pic_image1);
		pic_image2 = (ImageView) findViewById(R.id.pic_image2);

		pic1_layout = (LinearLayout) findViewById(R.id.pic1_layout);
		pic2_layout = (LinearLayout) findViewById(R.id.pic2_layout);

		pic1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showSelect(pic1);
			}
		});

		pic2 = (LinearLayout) findViewById(R.id.pic2);
		pic1.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showSelect(pic2);
			}
		});
		ok_Button = (Button) findViewById(R.id.ok_button);
		ok_Button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// userInfo.edit().putString("name",
				// email_edittext.getText().toString()).commit();
				// userInfo.edit().putString("pass",
				// password_edittext.getText().toString()).commit();
				// Intent intent = new Intent();
				// intent.setClass(ComplateUserInfo5Activity.this,
				// ComplateUserInfo4Activity.class);
				// startActivity(intent);

				new Thread(new Runnable() {

					@Override
					public void run() {
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("token", LoginInfo
								.getInstance().getAccess_token()));
						params.add(new BasicNameValuePair("puid", LoginInfo
								.getInstance().getPuid()
								+ ""));
						NameValuePair fileNVPair = new BasicNameValuePair(
								"photo", path);

						NetService.updateFile(ComplateUserInfo5Activity.this,
								Config.HOME_URL + uploadUrlString, params,
								fileNVPair);

					}
				}).start();
			}
		});

	}

	private void showSelect(LinearLayout view) {
		createListView(picSelect, 0, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.e("which", which + "");
				if (which == 0) {

					Intent captureImage = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);

					startActivityForResult(captureImage,
							SELECT_PHOTO_REQUEST_CODE);
				} else {
					// Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
					// getImage.addCategory(Intent.CATEGORY_OPENABLE);
					// // getImage.setType("image/jpeg");
					// getImage.setType("image/*");
					// getImage.putExtra("crop", "true");
					// getImage.putExtra("aspectX", 1);
					// getImage.putExtra("aspectY", 1);
					// getImage.putExtra("outputX", 320);
					// getImage.putExtra("outputY", 320);
					// getImage.putExtra("scale", true);
					// getImage.putExtra("noFaceDetection", true);
					// getImage.putExtra("setWallpaper", false);
					// getImage.putExtra("return-data", true);

					Intent i = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 调用android的图库
					startActivityForResult(i, GET_IMAGE);

					// startActivityForResult(Intent
					// .createChooser(getImage, "选择 "), GET_IMAGE);
				}
			}
		});
	}

	Dialog mDialog;

	private void createListView(CharSequence[] items, int checkedItem,
			final OnClickListener listener) {
		ListView listView = new ListView(this);
		int layout = R.layout.labi_select_dialog_singlechoice;
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
				this, layout, R.id.text1, items);
		listView.setAdapter(adapter);
		listView.setDivider(new ColorDrawable(Color.parseColor("#d1d1d1")));
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		if (checkedItem > -1 && checkedItem < items.length) {
			listView.setItemChecked(checkedItem, true);
			listView.setSelection(checkedItem);
		}
		listView.setBackgroundColor(Color.WHITE);
		listView.setCacheColorHint(Color.WHITE);
		if (listener != null) {
			listView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView parent, View v,
						int position, long id) {
					listener.onClick(mDialog, position);
					mDialog.dismiss();
				}
			});
		}
		mDialog = new Dialog(this);
		mDialog.setTitle("请选择");
		mDialog.addContentView(listView, new LayoutParams(FILL_PARENT,
				FILL_PARENT));
		mDialog.show();
	}

	Bitmap bmp;
	String path;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 完成照相后回调用此方法
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {

		case SELECT_PHOTO_REQUEST_CODE:

			switch (resultCode) {
			case Activity.RESULT_OK:// 照相完成点击确定
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.v("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				FileOutputStream b = null;
				File file = new File("/sdcard/pk4fun/");
				file.mkdirs();// 创建文件夹，名称为pk4fun //
				// 照片的命名，目标文件夹下，以当前时间数字串为名称，即可确保每张照片名称不相同。网上流传的其他Demo这里的照片名称都写死了，则会发生无论拍照多少张，后一张总会把前一张照片覆盖。细心的同学还可以设置这个字符串，比如加上“ＩＭＧ”字样等；然后就会发现sd卡中myimage这个文件夹下，会保存刚刚调用相机拍出来的照片，照片名称不会重复。
				String str = null;
				Date date = null;
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 获取当前时间，进一步转化为字符串
				date = new Date(resultCode);
				str = format.format(date);
				String fileName = "/sdcard/myImage/" + str + ".jpg";
				path = fileName;
				// sendBroadcast(fileName);
				pic_image1.setVisibility(View.VISIBLE);
				pic1_layout.setVisibility(View.GONE);
				pic_image1.setImageBitmap(bitmap);
				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				break;
			case Activity.RESULT_CANCELED:// 取消
				break;
			}
			break;
		case GET_IMAGE:
			switch (resultCode) {
			case Activity.RESULT_OK: {
				Uri uri = data.getData();
				Cursor cursor = getContentResolver().query(uri, null, null,
						null, null);
				cursor.moveToFirst();
				String imgNo = cursor.getString(0); // 图片编号
				String imgPath = cursor.getString(1); // 图片文件路径
				String imgSize = cursor.getString(2); // 图片大小
				String imgName = cursor.getString(3); // 图片文件名
				cursor.close();
				Options options = new BitmapFactory.Options();
				options.inJustDecodeBounds = false;
				options.inSampleSize = 10;
				Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options);
				path = imgPath;
				pic_image1.setVisibility(View.VISIBLE);
				pic1_layout.setVisibility(View.GONE);
				pic_image1.setImageBitmap(bitmap);
			}
				break;
			case Activity.RESULT_CANCELED:// 取消
				break;
			}
			break;
		}
		Log.e("filePath", path);
	} // @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// if (resultCode == RESULT_OK) {
	// if (GET_IMAGE == requestCode) { // 图库里获取。
	// final Bundle extras = data.getExtras();
	// if (extras != null) {
	// Bitmap bitmap = extras.getParcelable("data");
	// path = (String) extras.get("filePath");
	//
	// if (bitmap == null && path != null) {
	// BitmapFactory.Options opts = new BitmapFactory.Options();
	// opts.inSampleSize = 10;
	// bitmap = BitmapFactory.decodeFile(path, opts);
	// } else if (bitmap == null && path == null) {
	//
	// }
	//
	// pic_image1.setVisibility(View.VISIBLE);
	// pic1_layout.setVisibility(View.GONE);
	// pic_image1.setImageBitmap(bitmap);
	//
	// }
	// } else {
	//
	// Bitmap bitmap = data.getParcelableExtra("data");
	//
	// pic_image1.setVisibility(View.VISIBLE);
	// pic1_layout.setVisibility(View.GONE);
	// pic_image1.setImageBitmap(bitmap);
	//
	// }
	//
	// }
	//
	// }
}
